import React, { useState, useEffect, useRef } from 'react';
import { Radio, DatePicker, Select, Button, Card, Table, Pagination, Tag, message } from 'antd';
import { getChannels, getArticleList, deleteArticle } from '../../api/article'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import Preview from "../../components/Preview";
import './index.scss'
import { useNavigate } from 'react-router-dom';
const { RangePicker } = DatePicker;
const plainOptions = [{ id: -1, label: '全部' }, { id: 0, label: '草稿' }, { id: 1, label: '待审核' }, { id: 2, label: '审核通过' }, { id: 3, label: '审核失败' }];
const { Option } = Select;
const Article = () => {
  const navigate = useNavigate()
  const [value1, setValue1] = useState('');
  const [selectData, setSelectData] = useState([])
  const [selectv, setSelectv] = useState(<span style={{ color: '#bfbfbf' }}>请选择频道</span>)
  const [tableLoading, setTableLoading] = useState(true)
  const [date, setDate] = useState([])
  const [dateKey, setDateKey] = useState('')
  const [listParams, setListParams] = useState({
    page: 1,
    per_page: 10
  })
  const [tableData, setTableData] = useState([])
  const [total, setTotal] = useState(0)
  const [searchParam, setSearchParam] = useState({})
  const handleClickDel = async (row) => {
    console.log(row);
    const { id } = row
    await deleteArticle(id)
    message.success("删除成功！")
    let pages = {
      page: 1,
      per_page: 10
    }
    setListParams({ ...searchParam, ...pages })
  }
  const handleClickEdit = (row) => {
    const { id } = row
    navigate(`/index/publish?id=${id}`)
  }
  const columns = [
    {
      title: '缩略图',
      key: 'cover',
      dataIndex: 'cover',
      align: 'center',
      sorter: true,
      width: 150,
      render: (_, { cover }) => (
        <>
          <div>
            {/* <img src={cover.images[0]} alt="" style={{ width: '100%', height: 100, objectFit: 'cover' }} /> */}
            <Preview cover={cover} />
          </div>
        </>
      ),
    },
    {
      title: '文章标题',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      sorter: true,
    },
    {
      title: '审核状态',
      key: 'status',
      dataIndex: 'status',
      align: 'center',
      sorter: true,
      render: (_, { status }) => (
        <>
          {
            status === 1 ? <Tag color="magenta">未审核</Tag>
              : status === 2 ? <Tag color="green">审核成功</Tag> : ''
          }
        </>
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate',
      align: 'center',
      sorter: true,
    },
    {
      title: '评论数量',
      dataIndex: 'comment_count',
      key: 'comment_count',
      align: 'center',
      sorter: true,
    },
    {
      title: '点赞数量',
      dataIndex: 'like_count',
      key: 'like_count',
      align: 'center',
      sorter: true,
    },
    {
      title: '阅读数量',
      dataIndex: 'read_count',
      key: 'read_count',
      align: 'center',
      sorter: true,
    },
    {
      title: '操作',
      dataIndex: 'op',
      key: 'op',
      align: 'center',
      render: (_, row) => (
        <>
          <p><Button type="primary" icon={<EditOutlined />} onClick={() => handleClickEdit(row)}>编辑</Button></p>
          <p><Button type="primary" danger icon={<DeleteOutlined />} onClick={() => handleClickDel(row)}>删除</Button></p>
        </>
      ),
    }
  ];
  const onChange1 = ({ target: { value } }) => {
    console.log('radio1 checked', value);
    setValue1(value);
  };
  const handleChange = (value) => {
    console.log(value);
    setSelectv(value)
  };
  const getChannelsData = async () => {
    const res = await getChannels()
    setSelectData(res.data.channels)
  }
  const getChannelTableData = async () => {
    // const { data: { results: tableDataArr } } = await getArticleList({
    //   listParams
    // })
    try {
      setTableLoading(true)
      const { data } = await getArticleList(
        listParams
      )
      setTableData(data.results)
      setTotal(data.total_count)
    } finally {
      setTableLoading(false)
    }
  }
  const handleChangeCurrent = (page, pageSize) => {
    let pages = {
      page,
      per_page: pageSize
    }
    setListParams({ ...pages, ...searchParam })
  }
  const handleChangeDate = (v) => {
    console.log(v);
    setDate(v)
  }
  const handleClickSearch = () => {
    let params = {}
    params.status = value1
    if (typeof selectv === 'number') {
      params.channel_id = selectv
    }
    params.page = 1
    params.per_page = 10
    if (date.length) {
      params.begin_pubdate = date[0].format('YYYY-MM-DD')
      params.end_pubdate = date[1].format('YYYY-MM-DD')
    }
    console.log(selectv);
    setSearchParam(params)
    setListParams(listParams => ({ ...listParams, ...params }))
  }
  const handleClickRefush = () => {
    setDateKey(new Date())
    setSelectv(<span style={{ color: '#bfbfbf' }}>请选择频道</span>)
    setSearchParam({})
    let param = {
      page: 1,
      per_page: 10,
    }
    setListParams({ ...param })
  }
  useEffect(() => {
    getChannelsData()
  }, []);
  useEffect(() => {
    getChannelTableData()
  }, [listParams]);
  return (
    <div className='' style={{ width: '100%' }}>
      <Card
      >
        <div className="filter_container">
          <div className="filter_item">
            <div className="left_text">状态：</div>
            <div className="right_filter">
              <Radio.Group name="radiogroup" onChange={onChange1} defaultValue={-1}>
                {
                  plainOptions.map(item => <Radio key={item.id} value={item.id}>{item.label}</Radio>)
                }
              </Radio.Group>
            </div>
          </div>
          <div className="filter_item">
            <div className="left_text">频道：</div>
            <div className="right_filter">
              <Select style={{ width: 500 }} onChange={handleChange} placeholder="请选择频道" value={selectv}>
                {
                  selectData.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)
                }
              </Select>
            </div>
          </div>
          <div className="filter_item">
            <div className="left_text">日期：</div>
            <div className="right_filter">
              <RangePicker style={{ width: 500 }} onChange={handleChangeDate} key={dateKey} />
            </div>
          </div>
          <Button type="primary" style={{ marginLeft: '60px', width: 300 }} onClick={handleClickSearch}>筛选</Button>
          <Button style={{ marginLeft: '60px', width: 100 }} onClick={handleClickRefush}>重置</Button>
        </div>
      </Card>
      <Card style={{ marginTop: '30px' }}>
        <Table pagination={false} columns={columns} dataSource={tableData} loading={{ spinning: tableLoading, tip: "正在玩命加载..." }} sticky title={() => "文章数据列表"} scroll={{ x: 1300 }} rowKey="id" />
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 40 }}>
          <Pagination
            total={total}
            current={listParams.page}
            defaultPageSize={listParams.per_page}
            defaultCurrent={listParams.page}
            onChange={handleChangeCurrent}
          />
        </div>
      </Card >
    </div >
  );
}

export default Article;
